<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/12
 * Time: 20:47
 */
include "config.php";
include "status.php";
if($_SERVER["REQUEST_METHOD"]!="POST")
{
    print_r(json_encode(Status::$reg_nget));
    return;
}
$UID = $_POST["u_id"]; // 用户id
$GID = $_POST["gid"];//产品id


$CNAME = $_POST["goodsName"];//产品 名称
$CNPRICE = $_POST["newprice"];//产品价格
$COPRICE=$_POST["oldprice"];
$DISCOUNT=$_POST["discount"];
$CNAME1=$_POST["goodsName1"];
$CNUM = $_POST["num"];//产品数量
$CIMG = $_POST["img"];//产品图片
$CTOTAL = $CNPRICE * $CNUM;  //产品总金额

$sqlQuery = "SELECT * FROM cart WHERE u_id= ? ;";
$stmt = $conn->prepare($sqlQuery);
$stmt->bind_param("i", $UID);
$stmt->execute();
$queryResult = $stmt->get_result();

$flag=true;
while ($row=$queryResult->fetch_assoc()){
    if($row["g_id"]==$GID){
        $flag=false;
        break;
    }
}
if($flag==true){
    //没买过
    $sqlInert = "INSERT INTO cart (`c_name`,`c_nprice`,`c_num`,`c_img`,`c_total`,`u_id`,`g_id`,`c_oprice`,`c_name1`,`c_discount`)
VALUES(?,?,?,?,?,?,?,?,?,?)";
    $stmtI = $conn->prepare($sqlInert);
    $stmtI->bind_param("sssssiisss",$CNAME,$CNPRICE, $CNUM,$CIMG,$CTOTAL,$UID,$GID,$COPRICE,$CNAME1,$DISCOUNT);
    $stmtI->execute();

    if($stmtI->affected_rows>=1)
    {
        print_r(json_encode(array("msg" => "加入购车成功i", "status" => 1)));
    }
    else {
        print_r(json_encode(array("msg" => "加入购车失败i", "status" => -1)));
    }
    $stmtI->close();
}
else{
    //购物车中已存在
    $sqlUpdate = "UPDATE cart SET  c_num=c_num+? ,c_total=c_num*c_nprice WHERE u_id=?  and g_id=?";

    $stmtU = $conn->prepare($sqlUpdate);
    $stmtU->bind_param("iii", $CNUM,$UID,$GID);
    $stmtU->execute();

    if($stmtU->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功u", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败u", "status" => -1)));
    }
    $stmtU->close();
}
$conn->close();